/**
 * Created by LiuJie on 2017/1/3.
 * 浏览器缓存工具:LocalStorageUtils
 */
;
String.prototype.replaceAll = function (reallyDo, replaceWith) {
    return this.replace(new RegExp(reallyDo, ("gm")), replaceWith);
};
/**
 * 浏览器本地缓存
 * 支持cookie && localStorage
 * @param key
 * @constructor
 */
var WindowStorage = function(key){
    this.key =  key;
    //this.value = value;
    this.storage = window.localStorage ? window.localStorage : null;
};
WindowStorage.prototype = {
    setStorage:function(v){
        var _k = this.key,
            _v = v ;
        if(this.storage){
            this.storage.setItem(_k,_v);
        }else{
            $.cookie(_k, _v);
        }
    },
    getStorage:function(k){
        var _k = k ? k : this.key;
        if(this.storage){
            return this.storage.getItem(_k) ? this.storage.getItem(_k) : "";
        }else{
            return $.cookie(_k) ? $.cookie(_k) : "";
        }
    }
};


var LocalStorageUtils = function () {
    this._key = "SAAS_SYS_PRIVILEGE_ROOT";
    this._info = '';
    this._loaclStorage = window.sessionStorage ? window.sessionStorage : null;
    //当前路径
    this._path = window.location.pathname.substr(0, window.location.pathname.lastIndexOf('/') + 1);
};
LocalStorageUtils.prototype = {
    /**
     * 压缩json字符串
     * @param text
     * @returns {*}
     */
    deflateByPako:function(text){
        return pako.deflate(text, {to: 'string'})
    },
    /**
     * 解压缩json字符串
     * @param text
     * @returns {*}
     */
    inflateByPako:function(text){
        return pako.inflate(text, {to: 'string'})
    },
    /**
     * 将登录信息写入localstorage缓存，
     * 浏览器支持 html5-localstorage则用，不支持则通过cookie缓存
     * @param stringInfo
     */
    setCacheInfo: function (stringInfo) {
        this._info = stringInfo;
        if (this._loaclStorage) {
            this._loaclStorage.setItem(this._key, this._info);
        } else {
            var _path = this._path;
            var root_obj_string = this.deflateByPako(this._info);
            $.cookie(this._key, root_obj_string, {path: _path});
        }
    },
    /**
     * 获取缓存的登录信息
     */
    getCacheInfo: function () {
        if (this._loaclStorage) {
            return this._loaclStorage.getItem(this._key);
        } else {
            var roots_string = $.cookie(this._key) ? $.cookie(this._key) : null;
            var roots = this.inflateByPako(roots_string);
            return roots;
        }
    },
    removeCacheInfo: function () {
        if (this._loaclStorage) {
            this._loaclStorage.removeItem(this._key);
        } else {
            $.cookie(this._key,"",{path: this._path});
        }
    }
};

/**
 * 操作登录信息对象
 * @type {{setInfo}}
 */
var LoginInfoUtils = function ($) {
    var localStorageUtils,
        localInfo = {
            businessState:'',
            lgInfo: {},
            resInfo: []
            //sysInfo: []
        };

    var testSpanHtml = "<span class='testMenu'>试</span>";
    /**
     * 写入localstorage缓存登录信息(包含权限信息)
     * @param resInfo
     * @param lgInfo
     */
    function setLoginInfo(resInfo,lgInfo,businessState) {
        if (resInfo) {
            localInfo.resInfo = resInfo;
        }
        //if (sysInfo) {
        //    localInfo.sysInfo = sysInfo
        //}
        if (lgInfo) {
            localInfo.lgInfo = lgInfo;
        }
        if(businessState!=undefined){
            localInfo.businessState = businessState;
        }
        var _localInfo = getJSONString(localInfo);
        localStorageUtils.setCacheInfo(_localInfo);
    }

    /**
     * 获取换成的登录信息（包含权限信息）
     */
    function getLoginInfo(){
        var _cache_info = localStorageUtils.getCacheInfo();
        _cache_info = getJSONInfo(_cache_info);
        return _cache_info;
    }

    /**
     * 获取所有的权限信息
     * @returns {Array|*}
     */
    function getResInfo() {
        var _res_info = getLoginInfo();
        return _res_info.resInfo;
    }

    /**
     * 获取左侧二级菜单数据
     */
    function getLeftSecondMenuData(){
        var secondMenus = [];
        var _privileges = getResInfo();
        if (_privileges && _privileges.length) {
            for (var i = 0; i < _privileges.length; i++) {
                var _res = _privileges[i];
                var resList = _res["resList"];
                secondMenus = $.merge(secondMenus,resList);
            }
        }
        return secondMenus;
    }
    /**
     *根据左侧菜单resId获取菜单数据
     * @returns {boolean}
     */
    function getLeftMenuDataByResId(resId){
        var resList = getLeftSecondMenuData();
        if (resList && resList.length) {
            for (var j = 0; j < resList.length; j++) {
                var _secondMenu = resList[j],
                    _child_resId = _secondMenu["resId"];
                if(resId == _child_resId){
                    return _secondMenu;
                }
            }
        }
    }

    /**
     * 根据菜单resId获取菜单是否为试用菜单
     * @param menuId
     */
    function getIsTestMenu(resId){
        var _menuData = getLeftMenuDataByResId(resId);
        if(_menuData["pType"] === "1"){
            return true
        }
        return false
    }

    /**
     * 根据resid判断试用菜单是否过期
     * @param resId
     * @returns {boolean}
     */
    function getTestMenuIsOverLimit(resId){
        var _menuData = getLeftMenuDataByResId(resId);
        if(_menuData["isOverLimit"] === "1"){
            return true
        }
        return false
    }

    /**
     * 获取一级菜单、二级菜单权限信息（即左侧菜单栏的信息）
     */
    function getChildMenuInfos() {
        var _privileges = getResInfo(),
            opList = [];
        if (_privileges && _privileges.length) {
            for (var i = 0; i < _privileges.length; i++) {
                var _res = _privileges[i];
                var _res_childs = _res["resList"];
                var _res_childs_len = _res_childs.length;
                if (_res_childs && _res_childs_len) {
                    for (var j = 0; j < _res_childs_len; j++) {
                        var _res_item = _res_childs[j];//二级菜单 object
                        var _res_id = _res_item["resId"];//二级菜单 resId
                        var _op_list = _res_item["opList"];
                        var _op_list_len = _op_list.length;
                        for (var y = 0; y < _op_list_len; y++) {
                            var res_opId = "";
                            var _op_item = _op_list[y];
                            res_opId = _res_id + "_" + _op_item["opId"];
                            opList.push(res_opId);
                        }
                    }
                }

            }
        }
        return opList;
    }


    /**
     * 将json字符串转为json对象
     * @param info
     */
    function getJSONInfo(info) {
        try {
            if (!info) {
                return false;
            }
            var _info;
            if(info.indexOf("&quot;") != -1){
                _info = info.replaceAll("&quot;", "\"");
            }else{
                _info = info;
            }
            return JSON.parse(_info);
        } catch (e) {
            $.ErrorUtils.throwE(e);
        }
    }

    /**
     *将json对象转为json字符串
     */
    function getJSONString(info) {
        try {
            if (!info) {
                return false;
            }
            return JSON.stringify(info)
        } catch (e) {
            $.ErrorUtils.throwE(e);
        }
    }

    return {
        /**
         * 写入登录信息和权限信息
         * @param resInfo // 父权限信息
         * @param businessState // 业态信息
         * @param lgInfo //登录信息
         */
        setInfo: function (resInfo, lgInfo,businessState) {
            if (!localStorageUtils) {
                localStorageUtils = new LocalStorageUtils();
            }
            setLoginInfo(getJSONInfo(resInfo), getJSONInfo(lgInfo),businessState);
        },
        /**
         * 获取登录信息与权限信息
         * @returns {*}
         */
        getInfo: function () {
            return getLoginInfo();
        },
        /**
         * 设置左侧菜单权限
         */
        setParentMenuRes: function () {
            var _privileges = getResInfo(),
                $firstMenus = $("ul#res-menu-tree").find("li.treeview"),
                $secondMenus = $firstMenus.find("ul.treeview-menu").find("li.menu-active");
            if (_privileges && _privileges.length) {
                for (var i = 0; i < _privileges.length; i++) {
                    var _res = _privileges[i];
                    var resList = _res["resList"];
                    var p_resId = _res["resId"];
                    var $firstRes = $firstMenus.filter("[data-resId='" + p_resId + "']");
                    if ($firstRes.is(":hidden") && resList && resList.length) {
                        $firstRes.removeClass("dp-none");
                        for (var j = 0; j < resList.length; j++) {
                            var _secondMenu = resList[j],
                                _op_list = _secondMenu["opList"],
                                _child_resId = _secondMenu["resId"],
                                _pType = _secondMenu["pType"],
                                _isOverLimit  = _secondMenu["isOverLimit "],
                                _limitDate  = _secondMenu["limitDate"],
                                $secondRes = $secondMenus.filter("[data-child-resId='" + _child_resId + "']"),
                                $secondParent = $secondRes.parents("li.treeview"),
                                $menuTitle = $secondParent.find("div.treeview-menu-title").filter("[data-child-resId*='"+_child_resId+"']");
                            if ($secondRes.is(":hidden") && $secondParent.is(":visible") && _op_list && _op_list.length) {
                                if ($menuTitle && $menuTitle.length && $menuTitle.is(":hidden")) {
                                    $menuTitle.removeClass("dp-none");
                                }
                                $secondRes.removeClass("dp-none");
                                if(_pType === "1"){
                                    $secondRes.find("a").append(testSpanHtml);
                                }
                            }
                        }
                    }
                    //if (resList && resList.length) {
                    //
                    //}
                }
            }
        },
        /**
         * 控制子页面中具体的操作权限
         */
        setPagerOPRes: function () {
            var res_opList = getChildMenuInfos();
            if (res_opList.length) {
                for (var n = 0; n < res_opList.length; n++) {
                    var res_opId = res_opList[n];
                    var $res_span = $("[data-res-child-opId='" + res_opId + "']");
                    if ($res_span.is(":hidden")) {
                        $res_span.parents("div[data-opIds-parent-dom='true']").removeClass("dp-none");
                        $res_span.parents("span[data-opIds-parent-dom='true']").removeClass("dp-none");
                        $res_span.removeClass("dp-none");
                    }
                }
            }
        },

        loginInfo: {
            /**
             * 获取所有的登录信息(不包含权限信息)
             * @returns {localInfo.lgInfo|{}|*}
             */
            getAllInfo: function () {
                return getLoginInfo().lgInfo;
            },
            /**
             * 获取登录信息的门店id
             */
            getBranchId: function () {
                return getLoginInfo().lgInfo._branch_id;
            },

            getBranchName: function () {
                return getLoginInfo().lgInfo._branch_name;
            },

            getBranchType: function () {
                try {
                    return getLoginInfo().lgInfo._branch_type;
                } catch (e) {
                    $.ErrorUtils.throwE(e);
                }
            },
            getBusinessState:function(){
                try {
                    return getLoginInfo().businessState;
                } catch (e) {
                    $.ErrorUtils.throwE(e);
                }
            },
            getTenantCode:function(){
                try {
                    return getLoginInfo().lgInfo._tenant_code;
                } catch (e) {
                    $.ErrorUtils.throwE(e);
                }
            },
            /**
             * 登录的门店是否总部门店
             */
            isBranchHeader: function () {
                try {
                    var _branchType = this.getBranchType();
                    if (_branchType != undefined && _branchType == "0") {
                        return true;
                    } else {
                        return false;
                    }
                } catch (e) {
                    $.ErrorUtils.throwE(e);
                }
            }
        },
        privilegeInfo:{
            /**
             * 获取全部的权限信息
             */
            getAllInfo: function () {
                return getResInfo();
            },
            getParentResInfo: function () {

            },
            getChildResInfo: function () {

            },
            /**
             * 判断是否有指定的权限
             * 根据res_opid进行判断
             * @param resOpId example:5054_5200
             */
            isHasPrivilegeByResOpId:function(resOpId){
                var res_opList = getChildMenuInfos();
                if (res_opList.length) {
                    for (var n = 0; n < res_opList.length; n++) {
                        var res_opId = res_opList[n];
                        if(resOpId == res_opId){
                            return true;
                        }
                    }
                }
            },
            /**
             * 根据resId判断是否有左侧菜单权限
             * @param resId
             */
            isHasMenuPrivilegeByResId:function(resId){
                var _privileges = getResInfo();
                if (_privileges && _privileges.length) {
                    for (var i = 0; i < _privileges.length; i++) {
                        var _res = _privileges[i];
                        var resList = _res["resList"];
                        if (resList && resList.length) {
                            for (var j = 0; j < resList.length; j++) {
                                var _secondMenu = resList[j],
                                    _child_resId = _secondMenu["resId"];
                                if(resId == _child_resId){
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        },
        menuInfo:{
            /**
             * 菜单是否为试用菜单
             * @param menuId
             * @returns {*}
             */
            isTestMenu:function(menuId){
                return getIsTestMenu(menuId);
            },
            /**
             * 试用菜单是否过期
             * @param menuId
             * @returns {boolean}
             */
            isTestOverLimit:function(menuId){
                return getTestMenuIsOverLimit(menuId);
            }
        },
        vipManageInfo: {
            /**
             * 写入会员是否门店管理
             * @param isBranchManageVip
             */
            setVipBranchManageInfo: function (isBranchManageVip) {
                if (window.sessionStorage) {
                    sessionStorage.setItem("saas_isBranchManageVip_state", isBranchManageVip);
                } else {
                    var _path = window.location.pathname.substr(0, window.location.pathname.lastIndexOf('/') + 1);
                    $.cookie("saas_isBranchManageVip_state", isBranchManageVip, {path: _path});
                }
            },
            /**
             * 获取会员是否门店管理状态
             * @returns {null}
             */
            getVipBranchManageInfo: function () {
                if (window.sessionStorage) {
                    return sessionStorage.getItem("saas_isBranchManageVip_state");
                } else {
                    return $.cookie("saas_isBranchManageVip_state") ? $.cookie("saas_isBranchManageVip_state") : null;
                }
            }
        }
    }
}(jQuery);